package org.mspring.mlog.service;

import org.mspring.mlog.cache.CategoryCacheService;
import org.mspring.mlog.dao.CategoryDao;
import org.mspring.mlog.entity.Category;
import org.mspring.nbee.orm.dao.sql.builder.part.condition.SqlCondition;
import org.mspring.nbee.orm.dao.sql.pager.PageResult;
import org.mspring.nbee.orm.dao.sql.pager.Pager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author Gao Youbo
 * @since 2014-12-05 11:49:58
 */
@Service
public class CategoryService {

    private static final Logger LOG = LoggerFactory.getLogger(CategoryService.class);

    private CategoryDao categoryDao;
    private CategoryCacheService categoryCacheService;

    public Category findById(long id) {
        return categoryDao.findById(id);
    }

    public Category findByIdWithCache(long id) {
        Category category = categoryCacheService.getCategory(id);
        if (category == null) {
            category = findById(id);
            categoryCacheService.setCategory(id, category);
        }
        return category;
    }

    public PageResult<Category> list(List<SqlCondition> conditions, Pager pager) {
        return categoryDao.listPage(conditions, pager);
    }

    public List<Category> listAll() {
        List<Category> categoryList = categoryCacheService.getCategoryList();
        if (categoryList == null) {
            categoryList = categoryDao.listAll();
            categoryCacheService.setCategoryList(categoryList);
        }
        return categoryList;
    }

    @Transactional
    public boolean insert(Category category) {
        boolean flag = categoryDao.insert(category);
        if (flag) {
            categoryCacheService.removeCategoryList();
        }
        return flag;
    }

    @Transactional
    public boolean update(Category category) {
        boolean flag = categoryDao.update(category);
        if (flag) {
            categoryCacheService.removeCategory(category.getId());
            categoryCacheService.removeCategoryList();
        }
        return flag;
    }

    @Transactional
    public boolean deleteById(long id) {
        boolean flag = categoryDao.deleteById(id);
        if (flag) {
            categoryCacheService.removeCategory(id);
            categoryCacheService.removeCategoryList();
        }
        return flag;
    }

    @Autowired
    public void setCategoryDao(CategoryDao categoryDao) {
        this.categoryDao = categoryDao;
    }

    @Autowired
    public void setCategoryCacheService(CategoryCacheService categoryCacheService) {
        this.categoryCacheService = categoryCacheService;
    }
}